<?php
declare (strict_types=1);

namespace app\command;

use suck\newtype\EnumType;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;


/**
 * 吸取数据库生成迁移文件
 * Class SuckDb
 * @package app\command
 */
class SuckDb extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('shuckdb')
            ->setDescription('the shuckdb command');
    }

    protected function execute(Input $input, Output $output)
    {
        echo "正在生成迁移文件,请稍等...\n";

        //Console::call('migration:generate');
        $database_name = env('database.database');
        //print_r($database_name);
        // 获取数据库表名
        $table_names = Db::query("show tables from {$database_name}");
        print_r($table_names);
        $output->writeln('生成迁移文件完毕!');

    }

    public function index()
    {
        $database_name = env('database.database');
        //print_r($database_name);
        // 获取数据库表名
        $table_names = array_column(Db::query("show tables from {$database_name}"), 'Tables_in_' . $database_name);
        //dd($table_names);

        foreach ($table_names as $table) {
            $table_w = str_replace(env('database.prefix'), '', $table);
            //print_r($table);
            $arr = Db::query("select * from {$table}");
            $file_name = root_path() . "/database/initial/{$table_w}.php";
            // 创建文件
            touch($file_name);

            $file_obj = fopen($file_name, 'r+');
            //var_dump($arr);

            $arr_name = '$data';
            $file_data = var_export($arr, true);

            $data = <<<ARR
        <?php
        {$arr_name} = $file_data;
ARR;

            fwrite($file_obj, $data);
            echo "\n";
        }

        exit;
        $arr = Db::query("select * from yf_admin");

        $file_name = root_path() . "/database/initial/data.php";
        // 创建文件
        touch($file_name);
        // 写入文件
        $file_obj = fopen($file_name, 'r+');

        $arr_name = '$admin';
        $file_data = var_export($arr, true);

        $data = <<<ARR
        <?php
        {$arr_name} = $file_data;
ARR;

        fwrite($file_obj, $data);

        dd($arr);
        exit;
    }
}
